/**
 * 控件移动事件
 * */
;!function(window){
	"use strict";
	var MOD_NAME = 'wed';
	var document = window.document;
	var qs = window.qs;
	var STATUS = {};
	var mov = {};
	STATUS.mouseDown = false;
	STATUS.isDownControl = false;
	STATUS.isCanBePlaced = false;
	var formMenu;
	webEditor.poll(typeof YanCtMenu !="undefined",function(){
		formMenu = new YanCtMenu({
			ele:".LdgFormSubjectForm",
			menu:[
				{label:"修改", onclick:function(e,target){
					var selector = $(target.target);
					var id = selector.data("id");
					if(empty(id)){
						selector = $(target.target).parents("[data-id]");
						if(selector.length){
							id = selector.eq(0).data("id");
						}
					}
					if(!empty(id)){
						var editModal = MyModules.get('editModal');
						editModal.show(dragObj.getModule(id));
					}
					
				}}
				,{label:"删除", onclick:function(e,target){
					var selector = $(target.target);
					var id = selector.data("id");
					if(!id){
						console.log(selector.parents(".wrap-widget"));
						id = selector.parents(".wrap-widget").eq(0).data("id");
					}
					console.log(id);
					dragObj.removeDo(id);
				}}
				],
		});
	});

	$(document).on("drag", ".wrap-widget", function(event) {
        console.log(event);
    });
	//鼠标移动事件
	document.onmousemove = function (e) {		
		if (STATUS.mouseDown) {
			e = e || window.event;
			try { e.stopPropagation() } catch(e){
				e.cancelBubble = true;
			}
			try{
				leftControl.move(e);
			}catch(e){
				console.log(e);
			}			
		}else if(STATUS.isDownControl){
			e = e || window.event;
			try { e.stopPropagation() } catch(e){
				e.cancelBubble = true;
			}
			try{
				controlObj.move(e);
			}catch(e){
				console.log(e);
			}
		}
	}
    // 鼠标右键事件放开
	// document.addEventListener('mouseup', function(event) {
    //     // 处理 mouseup 事件
	// 	if(event.button == 2){
    //     	event.preventDefault(); //阻止事件冒泡
    //     	event.stopPropagation(); //阻止父级访问事件
    //     	console.log('Mouse up on:', event);
    //     	// console.log(event.target.parentNode.className);
    //     }else{
    //     }
    // });
	//鼠标放开事件
	$(document).on("mouseup", ".controlNameMove", function(thisEvent){
		thisEvent = thisEvent || window.event;
		try { thisEvent.stopPropagation() } catch(e){
			thisEvent.cancelBubble = true;
		}
		if(thisEvent.which===1){
			if(STATUS.mouseDown){
				STATUS.mouseDown = false;
				leftControl.clean();
				if (STATUS.isCanBePlaced) {
					STATUS.isCanBePlaced = false
					dragObj.controlDo();
				}
			}else{
				//处于放置的位置才能在中部区域增加控件
				if (STATUS.isDownControl) {
					dragObj.controlDo();				
				}
				STATUS.isDownControl = false;
				STATUS.isCanBePlaced = false;
				controlObj.clean();
			}
			dragObj.dragOff($(this));
		}else if(thisEvent.which===2){

		}
		// console.log("mouseup");
	});
		
	//中部控件删除事件
	$(document).on('click', '.controlDelete', function (thisEvent) {
		console.log('delete');
		thisEvent = thisEvent || window.event;
		try { thisEvent.stopPropagation() } catch(e){
			thisEvent.cancelBubble = true;
		}
		let id = $(this).parent().data('target'); //組件ID
		console.log(id);
		dragObj.removeDo(id);
	});

	/*
	*左边菜单鼠标事件
	*/
	$(document).on("mousedown", ".controlName", function(thisEvent){
		thisEvent = thisEvent || window.event;
		try { thisEvent.stopPropagation() } catch(e){
			thisEvent.cancelBubble = true;
		}
		if(thisEvent.which===1){
			//按下了控件,触发滑动事件里的效果
			STATUS.mouseDown = true;
			var options = controlObj.initMove($(this), thisEvent);
			leftControl.render($(this), options);
			var type = $(this).data('type');
			dragObj.initControl(type);
			$('.LdgDiyForm').removeClass('hasProperties');
		}
	});

	//中部控件按下事件
	$(document).on('mousedown', '.controlMove', function (thisEvent) {

		thisEvent = thisEvent || window.event;
		try { thisEvent.stopPropagation() } catch(e){
			thisEvent.cancelBubble = true;
		}
		if(thisEvent.which===1){
			var options = controlObj.initMove($(this), thisEvent);
			let id = $(this).parent().data('target'); //組件ID
			var selectoer = $(dragObj.wrapRoot).find("[data-id='"+id+"']");
			if(selectoer.parent().attr("web-drag")){
				selectoer.parent().remove();
			}else{
				selectoer.remove();
			}
			$("body > .LdgFormItemGroupButton").remove();
			dragObj.initControlById(id);
			controlObj.render($(this),options);
			STATUS.isDownControl = true;
		}
	});

	var leftControl = {
		hasUse:false,
		clean: function(){
			$('body > .controlNameMove').remove();
			this.hasUse = false;
		},
		move:function(e){
			if(this.hasUse){
				var rect = {
					left: e.clientX,
					top: e.clientY,
					right: e.clientX,
					bottom: e.clientY
				};
				var movX = mov.x - rect.left;
				var movY = mov.y - rect.top;
				var movLeft = mov.left - movX;
				var movTop = mov.top - movY; 
				$('body > .controlNameMove').css({
					left:movLeft,
					top:movTop
				});
				controlObj.moveItem(e);
			}			
		},
		render: function(selector, style){			
			var controlHtml = selector.prop('outerHTML');
			var styleHtml = 'class="controlName controlNameMove" ';
			styleHtml += 'style="width:' + style.elemWidth + 'px;';
			styleHtml += 'position: absolute;';
			styleHtml += 'background: #fff;';
			styleHtml += 'z-index: 100;';
			styleHtml += 'left: ' + style.left + ';';
			styleHtml += 'top: ' + style.top + ';';
			styleHtml += '"';
			controlHtml = controlHtml.replace('class="controlName"', styleHtml);
			$('body > .controlNameMove').remove();		
			$('body').append(controlHtml);
			this.hasUse = true;
		}
	};
	var controlObj = {
		hasUse:false,
		objectControl: {},
		initMove:function(selector, e, callback){
			var rect = {
				left: e.clientX,
				top: e.clientY,
				right: e.clientX,
				bottom: e.clientY
			};
			mov.x = e.clientX;
			mov.y = e.clientY;
			var paddingLeft = Number(selector.css("padding-left").replace("px", ''));
			var paddingRight = Number(selector.css("padding-right").replace("px", ''));
			var paddingTop = Number(selector.css("padding-top").replace("px", ''));
			var paddingBottom = Number(selector.css("padding-bottom").replace("px", ''));
	  		var elemWidth = selector.width() + paddingLeft + paddingRight + 2; // 控件的宽度
	    	var elemHeight = selector.height() + paddingTop + paddingBottom + 2; // 控件的高度

	    	// 滚动条高度
	    	var scrollArea = function(type){
	    		type = type ? 'scrollLeft' : 'scrollTop';
	    		return document.body[type] | document.documentElement[type];
	    	};

		    // 窗口宽高
	    	var winArea = function(type){
	    		return document.documentElement[type ? 'clientWidth' : 'clientHeight']
	    	};
	    	var margin = Number(selector.css("margin-left").replace("px", ''));
	    	var marginTop = Number(selector.css("margin-top").replace("px", ''));
	    	var left = rect.left;
	    	var top = rect.bottom;

	    	// 判断右侧是否超出边界
	    	if(left + elemWidth + margin > winArea('width')){
		      	left = winArea('width') - elemWidth - margin; // 如果超出右侧，则将面板向右靠齐
		      }
		    // 左侧是否超出边界
		      if(left < margin) left = margin;


		    // 判断底部和顶部是否超出边界
		    if(rect.bottom + elemHeight + margin > winArea()){ // 底部超出边界
			      // 优先判断顶部是否有足够区域显示完全，且底部不能超出边界
		    	if(rect.top > elemHeight + margin && rect.top <= winArea() ){
			        top = rect.top - elemHeight - margin*2; // 顶部有足够的区域显示
			      } else if(!opts.allowBottomOut){ // 顶部没有足够区域显示时，是否允许底部溢出
			        top = winArea() - elemHeight - margin*2; // 面板向底部靠齐
			        if(top < 0) top = 0; // 如果面板底部靠齐时，又溢出窗口顶部，则只能将顶部靠齐
			    }
			}

		    // 定位类型
			var position = selector.offset();
			var offsetX = 0;
			var offsetY = 0;
			mov.left = (position.left - 2 * margin - 9);
			mov.top = (position.top - marginTop);
			var style = {};
			// 设置坐标
			style.left = mov.left + 'px';
			style.top = mov.top + 'px';
			style.elemWidth = elemWidth;
		    // 防止页面无滚动条时，又因为弹出面板而出现滚动条导致的坐标计算偏差

			if(typeof callback != "undefined"){
				callback(style, e);
			}
			return style;
		},
		moveItem: function(e){
			var formArea = dragObj.getFormArea();
			var mouseX = e.clientX;
			var mouseY = e.clientY;
			if(mouseX>=formArea.left && mouseX <=formArea.right){
				if(mouseY < formArea.top){
					STATUS.isCanBePlaced = true;
					dragObj.containerIndex = [0];
					dragObj.indexs = {parent:"root",index:0};
				}else if( mouseY > formArea.bottom){
					STATUS.isCanBePlaced = false;
					dragObj.containerIndex = [-1];
				}else{
					dragObj.cleanPositionClass();
					if($(".main-container").children().length>0){
						if($(".main-container").children().eq(0)){
							var section_0 = $(".main-container").children().eq(0).offset().top;
							if(mouseY < section_0+20){
								STATUS.isCanBePlaced = true;
								dragObj.containerIndex = [-2];
								dragObj.indexs = {parent:"root",index:-2};
								$(".main-container").children().eq(0).addClass("placeLocationTop");
							}else{
								STATUS.isCanBePlaced = true;
								this.moveInForm(e);
							}
						}else{
							STATUS.isCanBePlaced = true;
							this.moveInForm(e);		
						}
					}else{
						STATUS.isCanBePlaced = true;
						dragObj.containerIndex = [-1];
						dragObj.indexs = {parent:"root",index:-1};
					}		
				}
			}else{
				STATUS.isCanBePlaced = false;
				dragObj.containerIndex = [-1];
			}
		},
		isInWrap:function(e, selector){
			var mouseX = e.clientX, mouseY=e.clientY,
			rect = selector.getClientRect() || selector.getBoundingClientRect();
			return rect.left <= mouseX && rect.right >= mouseX &&
				rect.bottom >= mouseY && rect.top <= mouseY;
		},
		moveInForm:function(e){
			var mouseX = e.clientX, mouseY=e.clientY;
			//是否可以放置
			STATUS.isCanBePlaced = true
			//获取中部的控件
			const containers = $("form.can-drag").children();

			dragObj.containerIndex = [-1];
			dragObj.indexs = {parent:"root",index:-1};
			for (var i = 0; i < containers.length; i++) {
				var container = containers[i];
				if(this.isInWrap(e, $(container))){
					dragObj.containerIndex = [i];
					dragObj.indexs = {parent:"root",index:i};
					this.moveInCanDrag(e, container);
					break;
				}
			}
		},
		moveInCanDrag:function(e, container){
			if($(container).children().length >0){
				const containers = $(container).children();
				for (var i = 0; i < containers.length; i++) {
					var container = containers[i];
					if(this.isInWrap(e, $(container))){
						if(this.moveInCanDrag(e, container)==-1){
							this.hoverEffect(container);
							var ids = this.nodeIds(container);
							ids.reverse();
							console.log(ids);
							dragObj.containerIndex = ids;
							return 0;
						}else{
							return 0;
						}
						break;
					}
				}
				return -1;
			}else{
				this.hoverEffect(container);
				var ids = this.nodeIds(container);
				ids.reverse();
				console.log(ids);
				dragObj.containerIndex = ids;
				return 1;
			}
		},
		fillNodeIndex:function(container, index){
			console.log($(container));
			var selector = $(container).parents("."+dragObj.wrapClass);
			if(selector.length==0){
				dragObj.indexs['parent'] = 'root';
			}else{
				dragObj.indexs['parent'] = selector.eq(0).data("id");
			}
			dragObj.indexs['index'] = index;
		},
		hoverEffect:function(last_node){
			if($(last_node).hasClass("wrap-widget")){
				$(last_node).addClass("placeLocationBottom");
			}else if($(last_node).hasClass(dragObj.dragClass)){
				$(last_node).addClass("placeLocationBottom");
			}else{
				this.hoverEffect($(last_node).parent());
			}
		},
		nodeIds:function(last_node){
			let result = [];
			if($(last_node).hasClass(dragObj.wrapClass)){
				if(!empty($(last_node).parent().attr("web-drag"))){
					result.push($(last_node).parent().index());
					this.fillNodeIndex($(last_node), $(last_node).parent().index());
				}else{
					result.push($(last_node).index());
					this.fillNodeIndex($(last_node), $(last_node).index());
				}				
			}else if($(last_node).hasClass(dragObj.dragClass)){
				var index_1 = $(last_node).index();
				if($(last_node).children().length==0){
					result.push(-1);
					index_1 = -1;
				}
				result.push($(last_node).index());
				this.fillNodeIndex($(last_node), index_1);
			}
			if(empty($(last_node).attr("web-drag"))){
				var ids = this.nodeIds($(last_node).parent());
				result = result.concat(ids);
			}
			return result;
		},
		render:function(selector, style){
			console.log(dragObj.control);
			var controlHtml = this.moveContainer(dragObj.control.name);
			controlHtml = $(controlHtml).addClass("controlNameMove").css({
				"width":"250px",
				"position":"absolute",
				"background":"#fff",
				"z-index": 100,
				"top": style.top,
				"left": style.left
			});
			
			$('body > .controlNameMove').remove();		
			$('body').append(controlHtml);
			this.hasUse = true;
		},
		clean: function(){
			$('body > .controlNameMove').remove();
			this.hasUse = false;
		},
		move:function(e){
			if(this.hasUse){
				var rect = {
					left: e.clientX,
					top: e.clientY,
					right: e.clientX,
					bottom: e.clientY
				};
				var movX = mov.x - rect.left;
				var movY = mov.y - rect.top;
				var movLeft = mov.left - movX;
				var movTop = mov.top - movY; 
				$('body > .controlNameMove').css({
					left:movLeft,
					top:movTop
				});
				controlObj.moveItem(e);
			}			
		},
		moveContainer: function(title){
			var str = `<div class="LdgFormItem controlName"><div class="LdgFormItemGroupButton"><i class="glyphicon glyphicon-move controlMove"></i></div>
			<div class="drag-container btn-group-justified"><a class="btn btn-default">${title}</a></div>`;
			return str;
		}
	}
	
	// 顯示佈局模塊
	$(document).on("click", "#add-row > .add", function(){
		$(this).hide();
		$("#elementor-add-new-section").show();
	});
	// 關閉佈局模塊
	$(document).on("click", "#add-row .elementor-add-section-close", function(){
		$("#elementor-add-new-section").hide();
		$("#add-row > .add").show();
	});

	// 添加佈局
	$(document).on("click", "#elementor-add-new-section .elementor-preset", function(){
		var id = $(this).data("structure");	
		dragObj.initControl('layout', id);
		dragObj.controlDo();
		$(".elementor-add-section-close").trigger("click");
	});
	
}(window, window.document);